package db

import (
	"time"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"

	"aicloud.cn/aicloud-operate/pkg/db/internal"
	"aicloud.cn/aicloud-operate/pkg/util"
)

type PostgresDb struct {
	internal.DB
}

func init() {
	RegisterFunc["postgres"] = func(url string) {
		dial := postgres.Open(url)
		db, err := gorm.Open(dial, &gorm.Config{})
		if err != nil {
			util.GetLogger().Fatalf("db init failed:%v", err)
		}
		sqlDb, _ := db.DB()
		sqlDb.SetMaxIdleConns(10)
		sqlDb.SetMaxOpenConns(50)
		sqlDb.SetConnMaxLifetime(time.Minute * 5)
		db.AutoMigrate(&struct{}{})
		DbClient = &PostgresDb{
			internal.DB{DB: db},
		}
	}
}
